
/**
 * The Sketchpad object.
 */
L.Sketchpad = L.Class.extend({
	includes: L.Mixin.Events,

	initialize: function(editorNode, options) {
		L.Util.setOptions(this, options);
		this._toolOptions = {};
		this._editorNode = editorNode;

		//canvas activo
		this._canvas = null;
		//canvases disponibles
		this._canvases = {};

		self._model = null;

		this._tool = new L.NullTool();
		this._toolOptions = new L.ToolOptions();

		this._disable_user_select();

		//mostrar mensaje que indica agregar diapositiva para comenzar
		this._emptyMessage(true);
	},

	getTool: function() {
		return this._tool;
	},

	/*setTool*/
	tool: function(value) {
		if (value === undefined) {
			return this._tool;
		}
		// finalizar la herramienta anterior
		if (value instanceof L.Tool) {
			this._tool.disable();  
			this._tool = value;
			if ( this._canvas ) {
				this._tool.enable(this);
			}
			this.fire('changeTool', this._tool.name);
		}
		return this; // function-chaining
	},

	toolOptions: function ( value ) {
		if ( value == undefined ) {
			return this._toolOptions;
		}
		for ( var key in value ) {
			this._toolOptions[key](value[key]);
		}

		if ( this._tool instanceof L.SelectTool ) {
			var elements = this._tool.getSelection();
			var color = this._toolOptions.color();
			var opacity = this._toolOptions.opacity();
			var width = this._toolOptions.width()*this.scale();

			for ( var n = elements.length; n--; ) {
				//console.log('elements[n]');console.log(elements[n]);
				var type = elements[n]._attrs.type;
				if ( type == 'text' ) {
					elements[n].attr({
						"fill": color,
						//"stroke-opacity": opacity,
						//"stroke-width": width,          
					});
				} else if( type == 'path' ) {
					elements[n].attr({
						"stroke": color,
						"stroke-opacity": opacity,
						"stroke-width": width,          
					});
				}
			}        
		}

		return this;
	},    


	// Sketch scaling
	scale: function(value, center){
		return this._canvas.scale(value, center);
	},

	undoable: function() {
		if(!this._canvas) return false;
		return this._canvas.getRoom().getHistory().undoable();
	},

	undo: function() {
		if (!this._canvas) return;
		//quitar seleccion para evitar problemas
		if ( this._tool instanceof L.SelectTool )
			this._tool.setSelection([]);

		this._canvas.getRoom().getHistory().undo();
		return this; // function-chaining
	},

	redoable: function() {
		if(!this._canvas) return false;
		return this._canvas.getRoom().getHistory().redoable();
	},

	redo: function() {
		if(!this._canvas) return;

		//quitar seleccion para evitar problemas
		if(this._tool instanceof L.SelectTool){
			this._tool.setSelection([]);
		}

		this._canvas.getRoom().getHistory().redo();
		return this; // function-chaining
	},

	clear: function() {
		if(!this._canvas) return;
		this._canvas.clearElements();
		return this; // function-chaining
	},


	copy: function() {
		if ( this._tool instanceof L.SelectTool ) {
			//se restablece la distancia de desplazamiento
			this._copy_paste_dx = 0;
			this._selectedElements = this._tool.getSelection();
		}  
	},

	paste: function() {
		if ( !this._selectedElements ) {
			return;
		}

		var elements = this._selectedElements;
		var copies = [];
		var canvas = this._canvas;
		var dx = this._copy_paste_dx += 20;

		for ( var i=0, len=elements.length; i<len; i++ ) {
			var el = elements[i];
			var s = el.serialize();
			uniqueId(s, true);
			var cp = L.ElementFactory.getElement(s);
			canvas.addElement(cp);
			//la referencia cambia, no se agrego el objeto sino una copia
			cp = canvas.getElement(cp.id);
			cp.move(dx, dx);
			copies.push(cp);
		}

		this.tool(new L.SelectTool(this));
		this._tool.setSelection(copies);
	},

	removeSelectedElements: function() {
		if(this._tool instanceof L.SelectTool){
			var selection = this._tool.getSelection();
			this._tool.emptySelection();

			var canvas = this._canvas;
			for(var i=0, len=selection.length; i<len; i++){     
				canvas.removeElement(selection[i].id);
			}
		} 
	},

	setModel: function(model) {
		var self = this;
		if (self._model) {
			self._model.off('roomAction', this.fireRoomAction, this);
		}
		self._model = model;
		self._model.on('roomAction', this.fireRoomAction, this);

		self._model.eachRoom(self.addCanvasFromRoom);
	},

	fireRoomAction: function ( params/*action_name,attr_list*/ ) {
		switch(params.action_name) {
		case "addRoom":
			this.addCanvasFromRoom(params.attr_list);
			break;
		case "removeRoom":
			this.removeCanvasFromRoom(params.attr_list);
			break;
		case "moveRoom":
			this.moveCanvasFromRoom(params.attr_list);
			break;
		}      
	},

	addCanvasFromRoom: function ( attr_list ) {
		
		if ( !Skt.config.USE_UI )
			return;
		
		var roomId = attr_list.roomId;
		var room = attr_list.room;
		var type = attr_list.type;
		var options = attr_list.options || {};

		var self = this;
		var canvases = this._canvases;

		if ( !canvases.hasOwnProperty(type) ) {
			canvases[type] = [];
		}
		

		//render
		var miniview = $('<li data-type="'+type+'" data-id="'+roomId+'" data-room="'+roomId+'" class="room minview" style="background-image: ' + room.getBackgroundImageCss + ';"></li>');
		if(Skt.tmanager.getRoomTask(roomId)){
			miniview.addClass("task-minview");
		}
		miniview.click( function(e) {
			self.setCurrentCanvas(roomId);
			e.stopPropagation();
		});
		

//		//render
//		var miniview = $('<li data-type="'+type+'" data-id="'+roomId+'" data-room="'+roomId+'" class="room" style="background-image: ' + room.getBackgroundImageCss + ';"></li>');
//		miniview.click( function(e) {
//			self.setCurrentCanvas(roomId);
//			e.stopPropagation();
//		});

		options.width = 1024;
		options.height = 672;
		options.type = type; 

		var canvas = new L.Canvas(miniview[0], room, options);
		canvas.scale(0.1, false);
		canvas.miniview = miniview[0];
		canvas.setMiniview(miniview[0]);
		canvas.on('change', this.updateMiniview, this);

		canvases[type].push(canvas);
		var div_container = null;
		if ( type == "personal" ) {
			div_container = $("#rooms_personal");
		} else if ( type == "groupal" ) {
			var group = room.getRoomList().getGroup();			
			div_container = $("#rooms-groupal-" + group.getId());
		} else if ( type == "question" ) {
			div_container = $("#rooms_question");
		} else if ( type == "answer" ) {
			div_container = $("#rooms_answer");
		} else if ( type == "screen" ) {
			div_container = $("#rooms_screen");
		} else {
			console.log("[WARNING] Sketchpad.addCanvasFromRoom: type desconocido :" + type);
		}

		div_container.prepend(miniview.wrap('<li></li>'));

		if ( room.getOwnerId() == Skt.user.id )
			this.setCurrentCanvas(roomId);

		this.fire('addCanvas', { 
			roomId: roomId,
			room: room,
			type: type,
			miniview: miniview
		});
		
	},

	removeCanvasFromRoom: function (attr_list) {
		
		if ( !Skt.config.USE_UI )
			return;
		
		var roomId = attr_list.roomId;
		var type = attr_list.type;

		var canvases = this._canvases[type];
		for ( var n = canvases.length; n--; ) {
			if ( canvases[n].getRoom().id == roomId ) {
				//quitar la minivista
				var miniview = canvases[n].miniview;
				miniview.parentNode.removeChild(miniview);

				//quitar canvas
				canvases.splice(n, 1);

				//cambiar el canvas actual de trabajo
				var newCurrent = n;
				if(newCurrent >= canvases.length) newCurrent = canvases.length-1;
				if(newCurrent >= 0){
					this.setCurrentCanvas(canvases[newCurrent].getRoom().id);
				}else{
					this.setCurrentCanvas();
				}
			}
		}
	
		
	},

	moveCanvasFromRoom: function(attr_list){
		
		if ( !Skt.config.USE_UI )
			return;
			
		var roomId = attr_list.roomId;
		var type = attr_list.type;
		var old_index = parseInt(attr_list.old_index);
		var new_index = parseInt(attr_list.new_index);

		var element_before_index = old_index > new_index ? new_index - 1 : new_index;
		//console.log("2) room.id:"+room.id+" old_index:"+old_index+" new_index:"+new_index);
		var canvases = this._canvases[type];
		for(var n=canvases.length; n--;){
			if(canvases[n].getRoom().id == roomId){
				var list = $(canvases[n].miniview).parent();
				var elem_to_sort = list.children('li').eq(old_index);
				if(element_before_index == -1){
					list.prepend(elem_to_sort);
				}else{
					var elem_before = list.children('li').eq(element_before_index);
					elem_before.after(elem_to_sort);
				}
				break;
			}
		}
		
		
	},

	_emptyMessage: function(show) {
		
		if ( !Skt.config.USE_UI )
			return;
		
		if (!this._startMessage) {
			if ( Skt.user.type == "tv" )
				this._startMessage = $('<div id="start_message">' +  Skt.user.name + ' ' + Skt.user.lastname + '</div>');
				else
				this._startMessage = $('<div id="start_message">Select a slide to start</div>');
			this._editorNode.before(this._startMessage);
		}
		if (show) {
			this._editorNode.css("visibility", "hidden");
			this._startMessage.css("visibility", "visible");
		} else {
			this._editorNode.css("visibility", "visible");
			this._startMessage.css("visibility", "hidden");
		}

		
	},

	setCurrentCanvas: function(id, ignoreFollowing) {
		
		if ( !Skt.config.USE_UI )
			return;
		
		if (!id) {
			console.log("[WARNING] Sketchpad.setCurrentCanvas: sin id de canvas");
			this._emptyMessage(true);
			return;
		}
		
		var canvas = this._findCanvas(id);
		
		if ( canvas == null ) {
			console.log("[WARNING] Sketchpad.setCurrentCanvas: canvas not found");
			return;
		}
		
		var room = canvas.getRoom();

		console.log('ignoreFollowing');
		console.log(ignoreFollowing);
		
		console.log("!ignoreFollowing && Skt.teacherMonitor.isFollowingEnabled() && Skt.teacherMonitor.getTeacherRoomId() != null && Skt.user.type != 'teacher'");
		console.log(!ignoreFollowing 
				&& Skt.teacherMonitor.isFollowingEnabled()
				&& Skt.teacherMonitor.getTeacherRoomId() != null
				&& Skt.user.type != 'teacher');
		
		if ( !ignoreFollowing 
				&& Skt.teacherMonitor.isFollowingEnabled()
				&& Skt.teacherMonitor.getTeacherRoomId() != null
				&& Skt.user.type != 'teacher' ) 
		{
			if ( Skt.user.type == 'tv' && (room.getType() != 'screen' || room.getType() != 'question') )
				return;
			else if ( room.getType() == 'screen' || room.getType() == 'question' ) {
				if ( this._findCanvas(Skt.teacherMonitor.getTeacherRoomId()) != null ) {
					id = Skt.teacherMonitor.getTeacherRoomId();
					canvas = this._findCanvas(id);
					room = canvas.getRoom();
				}
			}
		}

		if (this._canvas) {
			if (this._canvas.getRoom().id == id) {
				console.log("[WARNING] Sketchpad.setCurrentCanvas: new and old canvas are the same");
				return;
			}
			this._tool.disable();

			var svgNode = this._canvas.getSVGNode()[0];
			var miniview = this._canvas.getMiniview();
			var old = miniview.firstChild;
			if (old)
				miniview.removeChild(old);
			miniview.appendChild(svgNode);

			var moderator = this._canvas.getRoom().getRoomModerator();
			moderator.userLeave(Skt.user.id);
			moderator.off('userEvent',this._currentUsersChanged, this);

			this._canvas.scale(0.1, false);
			this._canvas.onRemove(this);
		}
		
		this._canvas = canvas;
		var svgNode = this._canvas.getRaphael().canvas;
		this._editorNode.append(svgNode);

		this._canvas.scale(1);
		this._canvas.onAdd(this);
		this.updateMiniview(this._canvas);

		$(".room").removeClass('selected');
		$(this._canvas.getMiniview()).addClass('selected');

		this._tool.enable(this);
		this._emptyMessage(false);

		$('#editor').css('background-image', room.getBackgroundImageCss());

		var moderator = room.getRoomModerator();
		moderator.on('userEvent', this._currentUsersChanged, this);
		moderator.userJoin(Skt.user.id);
		
		this.fire("currentCanvasChange", {
			canvas: this._canvas,
			roomId: room.id
		});

//		var all_canvases = this._canvases;
//		for ( var type in all_canvases) {
//			if (all_canvases.hasOwnProperty(type)) {
//				var canvases = all_canvases[type];
//				for (var i = 0, n = canvases.length; i < n; i++) {
//
//					var room = canvases[i].getRoom(); 
//					if (room.id == id) {
//						this._canvas = canvases[i];
//						var svgNode = this._canvas.getRaphael().canvas;
//						this._editorNode.append(svgNode);
//
//						this._canvas.scale(1);
//						this._canvas.onAdd(this);
//						this.updateMiniview(this._canvas);
//
//						$(".room").removeClass('selected');
//						$(this._canvas.getMiniview()).addClass('selected');
//
//						this._tool.enable(this);
//						this._emptyMessage(false);
//
//						$('#editor').css('background-image', room.getBackgroundImageCss());
//
//						var moderator = room.getRoomModerator();
//						moderator.on('userEvent', this._currentUsersChanged, this);
//						moderator.userJoin(Skt.user.id);
//						
//						this.fire("currentCanvasChange", {
//							canvas: this._canvas,
//							roomId: room.id
//						});
//
//						break;
//					}
//
//				}
//			}
//		}
	},
	
	_findCanvas: function(roomId) {
		var all_canvases = this._canvases;
		for ( var type in all_canvases) {
			if (all_canvases.hasOwnProperty(type)) {
				var canvases = all_canvases[type];
				for (var i = 0, n = canvases.length; i < n; i++) {
					if ( canvases[i].getRoom().id == roomId )
						return canvases[i];
				}
			}
		}
		return null;
	},

	_currentUsersChanged: function(params) {
		this.fire('currentUsersChanged', params);	
	},

	updateMiniview: function(canvas) {
		
		if ( !Skt.config.USE_UI )
			return;
		
		if ( canvas == this._canvas ) {
			var svgNode = canvas.getSVGNode()[0];
			var clone = svgNode.cloneNode(true);
			clone.style.left = 0;
			clone.style.top = 0;
			clone.setAttribute('width', 102.4);
			clone.setAttribute('height', 67.2);
			clone.setAttribute('viewBox', '0 0 1024 672');

			var old = canvas.getMiniview().firstChild;
			if ( old )
				canvas.getMiniview().removeChild(old);
			canvas.getMiniview().appendChild(clone);
			$(canvas.getMiniview()).css('background-image',canvas.getRoom().getBackgroundImageCss());      
		}
		
	},


	removeRoom: function(roomId){
		if(this._canvas || roomId){
			var id = roomId || this._canvas.getRoom().id;
			this._model.removeRoom(id);
		}
	},

	moveRoom: function(roomId, old_index, new_index){
		this._model.moveRoom(roomId, old_index, new_index);
	},

	copyRoom: function (roomId) {
		if ( this._canvas || roomId ) {
			var id = roomId || this._canvas.getRoom().id;
			this._model.copyRoom(id);
		}
	},

	pasteRoom: function (roomId) {
		if ( this._canvas || roomId ) {
			var id = roomId || this._canvas.getRoom().id;
			this._model.pasteRoom(id);
		}
	},

	getCurrentCanvas: function(){
		return this._canvas;
	},

	getLayer: function(){
		//definir layer de trabajo
		var layer = "default";
		return layer;
	},

	// Miscellaneous methods
	//------------------

	_disable_user_select: function() {
		$("*").css("-webkit-user-select", "none");
		$("*").css("-moz-user-select", "none");
		if (jQuery.browser.msie) {
			$("body").attr("onselectstart", "return false;");
			$("input").removeAttr("onselectstart");
		}
		$("input, textarea").css("-webkit-user-select", "text");
		$("input, textarea").css("-moz-user-select", "text");
	},

	_enable_user_select: function() {
		$("*").css("-webkit-user-select", "text");
		$("*").css("-moz-user-select", "text");
		if (jQuery.browser.msie) {
			$("body").removeAttr("onselectstart");
		}
	},    


});
